<template>
  <CustomDialog ref="customDialog" width="600px" :title="dialogProps.title" :isView="dialogProps.isView"
    :onSubmit="handleSubmit" :onClose="handleClose">
    <template #header>
      {{ `${dialogProps.title}用户` }}
    </template>
    <template #content>
      <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :disabled="dialogProps.isView"
        :model="dialogProps.row" :hide-required-asterisk="dialogProps.isView">
        <el-form-item label="用户姓名" prop="username">
          <BInput v-model="dialogProps.row!.username" placeholder="请填写用户姓名" clearable :inputProps="{ maxlength: 50 }" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="dialogProps.row!.phoneNumber" placeholder="请填写手机号码" clearable @input="handlePhoneNumber" />
        </el-form-item>
        <el-form-item label="登录账号" prop="loginName">
          <el-input v-model="dialogProps.row!.loginName" placeholder="请填写登录账号" clearable :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="dialogProps.row!.password" placeholder="请填写密码" clearable type="password" show-password />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="dialogProps.row!.sex" placeholder="请选择性别" clearable>
            <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门/职位" prop="jobIds">
          <el-tree-select v-model="dialogProps.row!.jobIds" :data="treeSelectData" multiple filterable check-strictly
            :props="treeSelectProps" :default-value="dialogProps.row.jobIds">

          </el-tree-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogProps.row!.status" placeholder="请选择状态" clearable>
            <el-option v-for="item in userStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="customDialog?.acceptParams(false)">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import { genderType, userStatus } from "@/utils/dict";
import { ElMessage, FormInstance } from "element-plus";
import CustomDialog from "@/components/Dialog/CustomDialog.vue";
import BInput from "@/components/BaseComponents/BInput.vue";
import { userDetails, getPostTreeList } from "@/api/basic/user";
import { useDataStore } from '@/stores/modules/data'
import { debounce } from 'lodash';

const dataStore = useDataStore()

const rules = reactive({
  username: [{ required: true, message: "用户姓名必填" }],
  phoneNumber: [{ required: true, message: "手机号码必填" }, { pattern: /^1[3456789]\d{9}$/, message: '请输入有效的手机号码' }],
  loginName: [{ required: true, message: "登录账号必填" }],
  password: [{ required: true, message: "登录密码必填" }],
  sex: [{ required: true, message: "性别必选" }],
  jobIds: [{ required: true, message: "部门/职位必填" }],
  status: [{ required: true, message: "状态必选" }],
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {
    id: '',
    username: '',
    phoneNumber: '',
    loginName: '',
    password: '',
    sex: '',
    jobIds: [],
    status: ''
  },
});

const customDialog = ref<InstanceType<typeof CustomDialog>>();
const isEdit = ref(false)

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  // dialogProps.value = params;
  //修改，使新增时数据不清除
  dialogProps.value.api = params.api;
  dialogProps.value.getTableList = params.getTableList;
  dialogProps.value.title = params.title;
  params.title == '新增' ? isEdit.value = true : isEdit.value = false
  dialogProps.value.isView = params.isView;
  dialogProps.value.row.password = 'gq123456';
  if (JSON.stringify(params.row) !== '{}') {
    const res: any = await userDetails(params.row.id);
    dialogProps.value.row = { ...res };
  }

  customDialog.value?.acceptParams(true);
};

watch(() => dialogProps.value,
  (newValue) => {
    // console.log('66666', newValue);
  }, { immediate: true });

interface TreeSelectNode {
  value: number;
  label: string;
  children?: TreeSelectNode[];
  disabled?: boolean;
}

//转换为树形结构
const convertToTreeSelectData = (data: any[]): TreeSelectNode[] => {
  return data.map(node => {
    const treeSelectNode: TreeSelectNode = {
      value: node.id,
      label: node.name,
      children: node.children ? convertToTreeSelectData(node.children) : undefined,
      disabled: node.deptId ? false : true
    };
    return treeSelectNode;
  });
}

onMounted(async () => {
  await dataStore.fetchDepartmentList()
});

interface Job {
  id: number;
  deptId: number;
  jobName: string;
}

interface Dept {
  id: number;
  name: string;
  userTotal: number | null;
  jobList: Job[] | null;
  children: any[] | null;
  pid: number;
  deptId: any
}

function transformTree(treeData: Dept[]): Dept[] {
  const traverse = (node: Dept) => {
    if (node.children) {
      node.children = node.children.map(traverse);
    }
    if (node.jobList && node.jobList.length > 0 && !node.children) {
      node.children = node.jobList.map(job => ({
        id: job.id,
        name: job.jobName,
        deptId: job.deptId
      }));
    }

    if (node.jobList && node.jobList.length > 0 && node.children && node.children.length > 0) {
      const existingIds = new Set(node.children.map(child => child.id));
      const newChildren = node.jobList
        .filter(job => !existingIds.has(job.id))
        .map(job => ({
          id: job.id,
          name: job.jobName,
          deptId: job.deptId
        }));
      node.children = node.children.concat(newChildren);
    }

    return node;
  };

  return treeData.map(traverse);
}

// 获取部门树
const treeSelectData = ref<TreeSelectNode[]>([]);
const getOrganicTreeList = async () => {
  try {
    const res = await getPostTreeList();
    const data1 = transformTree(res);
    treeSelectData.value = convertToTreeSelectData(data1)
  } catch (error) {
    console.log('获取部门列表失败', error);
  }
}
getOrganicTreeList()



const handlePhoneNumber = debounce((value: any) => {
  if (value && value.length === 11) {
    dialogProps.value.row.loginName = value
  }
}, 600)

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}用户成功！` });
      dialogProps.value.getTableList!();
      customDialog.value?.acceptParams(false);
      ruleFormRef.value?.resetFields();
    } catch (error) {
      console.log(error);
    }
  });
};

const handleClose = () => {
  customDialog.value?.acceptParams(false);
  if (dialogProps.value.title !== '新增') {
    dialogProps.value.row = {}
  }
};

const treeSelectProps = {
  value: 'value',
  label: 'label',
  children: 'children'
};

defineExpose({
  acceptParams
});
</script>
